/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * IngresoSistema.java
 *
 * Created on 13-ene-2013, 20:02:48
 */
package sisvoto.vista;

import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import sisvoto.DAO.ConsultasBD;
import sisvoto.ModeloDAO.SesionLoginDAO;
import sisvoto.Utiles.Mensajes;
import sisvoto.modelo.EleccionActual;
import sisvoto.modelo.JornadaElectoral;
import sisvoto.modelo.PrivilegioUsuario;
import sisvoto.modelo.SesionLogin;

/**
 *
 * @author Dianita
 */
public class IngresoSistema extends javax.swing.JDialog {

    sisvoto.modelo.Usuario usuario;
    ConsultasBD consulta;
    ArrayList<sisvoto.modelo.Usuario> usuarios;
    ArrayList<PrivilegioUsuario> privilegios;
    EleccionActual eleccionactual;

    /** Creates new form IngresoSistema */
    public IngresoSistema(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.usuario = new sisvoto.modelo.Usuario();
        this.consulta = new ConsultasBD();
        this.usuarios = new ArrayList<sisvoto.modelo.Usuario>();
        this.privilegios = new ArrayList<PrivilegioUsuario>();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        imagePanel2 = new com.mycsistemas.swingec.panel.ImagePanel();
        curvesPanel2 = new com.mycsistemas.swingec.panel.CurvesPanel();
        jLblIngSist1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLblIngSist2 = new javax.swing.JLabel();
        btnVoto = new javax.swing.JButton();
        imagePanel1 = new com.mycsistemas.swingec.panel.ImagePanel();
        curvesPanel1 = new com.mycsistemas.swingec.panel.CurvesPanel();
        jBtnIngCancelar = new javax.swing.JButton();
        btnAceptar = new javax.swing.JButton();
        jLblIngNombre = new javax.swing.JLabel();
        jLblIngClave = new javax.swing.JLabel();
        txtClave = new javax.swing.JPasswordField();
        jLblIngSist = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Ingreso al Sistema");

        jTabbedPane1.setFont(new java.awt.Font("Georgia", 3, 14));

        imagePanel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sisvoto/Recursos/''_10102012_1738.jpeg"))); // NOI18N

        curvesPanel2.setLayout(null);

        jLblIngSist1.setFont(new java.awt.Font("Georgia", 3, 18));
        jLblIngSist1.setForeground(new java.awt.Color(255, 255, 255));
        jLblIngSist1.setText("*** Sistema de Elecciones ***");
        curvesPanel2.add(jLblIngSist1);
        jLblIngSist1.setBounds(52, 21, 270, 21);

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sisvoto/Recursos/User1.png"))); // NOI18N
        curvesPanel2.add(jLabel2);
        jLabel2.setBounds(67, 50, 80, 60);

        jLblIngSist2.setFont(new java.awt.Font("Georgia", 3, 18));
        jLblIngSist2.setForeground(new java.awt.Color(255, 255, 255));
        jLblIngSist2.setText("BIENVENIDO");
        curvesPanel2.add(jLblIngSist2);
        jLblIngSist2.setBounds(160, 60, 130, 37);

        btnVoto.setFont(new java.awt.Font("Tahoma", 1, 11));
        btnVoto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sisvoto/Recursos/visto.png"))); // NOI18N
        btnVoto.setText("EJERCER EL VOTO");
        btnVoto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVotoActionPerformed(evt);
            }
        });
        curvesPanel2.add(btnVoto);
        btnVoto.setBounds(70, 120, 208, 54);

        javax.swing.GroupLayout imagePanel2Layout = new javax.swing.GroupLayout(imagePanel2);
        imagePanel2.setLayout(imagePanel2Layout);
        imagePanel2Layout.setHorizontalGroup(
            imagePanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(curvesPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
        );
        imagePanel2Layout.setVerticalGroup(
            imagePanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(curvesPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("ELECTOR", imagePanel2);

        imagePanel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sisvoto/Recursos/''_10102012_1738.jpeg"))); // NOI18N

        jBtnIngCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sisvoto/Recursos/DeleteRed.png"))); // NOI18N
        jBtnIngCancelar.setText("Cancelar");
        jBtnIngCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnIngCancelarActionPerformed(evt);
            }
        });

        btnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sisvoto/Recursos/tick_32.png"))); // NOI18N
        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        jLblIngNombre.setFont(new java.awt.Font("Elephant", 0, 14));
        jLblIngNombre.setForeground(new java.awt.Color(255, 255, 255));
        jLblIngNombre.setText("Usuario:");

        jLblIngClave.setFont(new java.awt.Font("Elephant", 0, 14));
        jLblIngClave.setForeground(new java.awt.Color(255, 255, 255));
        jLblIngClave.setText("Clave:");

        txtClave.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtClaveKeyPressed(evt);
            }
        });

        jLblIngSist.setFont(new java.awt.Font("Georgia", 3, 18));
        jLblIngSist.setForeground(new java.awt.Color(255, 255, 255));
        jLblIngSist.setText("*** Ingreso al Sistema***");

        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtNombreKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout curvesPanel1Layout = new javax.swing.GroupLayout(curvesPanel1);
        curvesPanel1.setLayout(curvesPanel1Layout);
        curvesPanel1Layout.setHorizontalGroup(
            curvesPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(curvesPanel1Layout.createSequentialGroup()
                .addGroup(curvesPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(curvesPanel1Layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addGroup(curvesPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLblIngClave, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLblIngNombre, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(curvesPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(txtNombre, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtClave, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)))
                    .addGroup(curvesPanel1Layout.createSequentialGroup()
                        .addGap(61, 61, 61)
                        .addComponent(btnAceptar)
                        .addGap(18, 18, 18)
                        .addComponent(jBtnIngCancelar))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, curvesPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLblIngSist, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(38, Short.MAX_VALUE))
        );
        curvesPanel1Layout.setVerticalGroup(
            curvesPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(curvesPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLblIngSist)
                .addGap(20, 20, 20)
                .addGroup(curvesPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(curvesPanel1Layout.createSequentialGroup()
                        .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(txtClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(curvesPanel1Layout.createSequentialGroup()
                        .addComponent(jLblIngNombre)
                        .addGap(18, 18, 18)
                        .addComponent(jLblIngClave)))
                .addGap(18, 18, 18)
                .addGroup(curvesPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBtnIngCancelar)
                    .addComponent(btnAceptar))
                .addContainerGap(27, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout imagePanel1Layout = new javax.swing.GroupLayout(imagePanel1);
        imagePanel1.setLayout(imagePanel1Layout);
        imagePanel1Layout.setHorizontalGroup(
            imagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(curvesPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        imagePanel1Layout.setVerticalGroup(
            imagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(curvesPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("ADMINISTRADOR", imagePanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnVotoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVotoActionPerformed
// TODO add your handling code here:
    //consulta.validarIntervaloFecha("JornadaElectoral", "FechaInicio", "FechaFin", new Date());
    ArrayList<EleccionActual> eleccionesactuales = (ArrayList<EleccionActual>) new ConsultasBD().buscarPOR("EleccionActual", "estado", "'INICIADO'");
    if (eleccionesactuales.isEmpty()) {
        new Mensajes().StandarWarning(this, "Las Elecciones Aún No Han Iniciado");
        return;
    } else {
        this.eleccionactual = eleccionesactuales.get(0);
        ArrayList<JornadaElectoral> jornadas = new ArrayList<>();
        jornadas = (ArrayList<JornadaElectoral>) consulta.validarIntervaloFecha("JornadaElectoral", "FechaInicio", "FechaFin", new Date(), "'" + eleccionactual.getEleccion().getId() + "'");
        int periodo = jornadas.size();
        if (periodo != 0 && periodo != -1) {
            AutenticacionElector au = new AutenticacionElector(null, true, eleccionactual);
            au.setLocationRelativeTo(this);
            au.setVisible(true);
        } else {
            new Mensajes().StandarWarning(this, "         No es Posible Ejercer el Voto Debido a las \n Configuraciones de Fecha de la Jornada Electoral \n      >>CONSULTE CON EL ADMINISTRADOR<< ");
        }

    }
}//GEN-LAST:event_btnVotoActionPerformed

private void jBtnIngCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnIngCancelarActionPerformed
// TODO add your handling code here:
    System.exit(0);
}//GEN-LAST:event_jBtnIngCancelarActionPerformed

private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
// TODO add your handling code here:
    if (validarcampos()) {
        long contador = consulta.ContadorRegistros("Usuario", "nombre");
        if (contador != 0 && contador != -1) {
            usuarios = (ArrayList<sisvoto.modelo.Usuario>) consulta.buscarPOR2("Usuario", "nombre", "'" + txtNombre.getText() + "'", "password", "'" + txtClave.getText() + "'");
            if (usuarios.isEmpty()) {
                new Mensajes().StandarWarning(this, "Usuario No Encontrado: Verifique los Datos de Acceso");
            } else {
              
                usuario = usuarios.get(0);
                
                if(usuario.getNombre().equals(txtNombre.getText())){
                    if(!usuario.getPassword().equals(txtClave.getText())){
                        new Mensajes().StandarWarning(this, "La Contraseña es Incorrecta");
                        return;
                    }
                }else{
                    new Mensajes().StandarWarning(this, "El usuario es Incorrecto");
                    return;
                }        
                String acceso = usuario.getIdPrivilegio().getAcceso();

                ArrayList<SesionLogin> sesiones = (ArrayList<SesionLogin>) new ConsultasBD().buscarPOR2("SesionLogin", "usuario", "'" + String.valueOf(usuario.getId()) + "'", "sesion", "'ACTIVO'");
                int sl = sesiones.size();
                if (sl == 0) {
                    SesionLogin sesion = new SesionLogin();
                    sesion.setFechaAcceso(new Date());
                    sesion.setUsuario(this.usuario);
                    sesion.setSesion("ACTIVO");
                    SesionLoginDAO sesDAO = new SesionLoginDAO(sesion);
                    try {
                        sesDAO.persist();
                    } catch (Exception ex) {
                        Logger.getLogger(IngresoSistema.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    if (acceso.equalsIgnoreCase("TOTAL")) {
                        this.dispose();
                        sisvoto.vista.Principal principal = new sisvoto.vista.Principal(sesion);
                        principal.setLocationRelativeTo(this);
                        principal.setVisible(true);
                    } else {
                        this.dispose();

                        /*AdministrarElector ae = new AdministrarElector(null, true);
                        ae.setLocationRelativeTo(this);
                        ae.setVisible(true);*/
                        sisvoto.vista.Principal principal = new sisvoto.vista.Principal(sesion);
                        principal.setLocationRelativeTo(this);
                        principal.getMenuconf().setEnabled(false);
                        principal.getMenuelec().setEnabled(false);
                        principal.getMenuinstitucion().setEnabled(false);
                        principal.getMenupart().setEnabled(false);
                        principal.getMenuusu().setEnabled(false);
                        principal.setVisible(true);
                    }
                } else {
                    if (new Mensajes().ConfirmacionDialogowarning(this, "Éste Usuario ya Tiene una Sesión Activa. \n  ¿Desea Cerrar la Sesión Anterior?") == 0) {
                        SesionLogin ses = sesiones.get(0);
                        ses.setSesion("INACTIVO");
                        ses.setFechaSalida(new Date());
                        SesionLoginDAO sdao = new SesionLoginDAO(ses);
                        try {
                            sdao.update();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }

            }
        } else {
            if (validaradmin()) {
                new Mensajes().StandarWarning(this, "Ingrese Un Nuevo Usuario Administrador");
                NuevoUsuario u = new NuevoUsuario(null, true);
                u.setLocationRelativeTo(this);
                u.setTitle("Nuevo Usuario");
                u.setVisible(true);
            } else {
                new Mensajes().StandarWarning(this, "Ingrese el Usuario Administrador por Defecto del Sistema \n                 Para Configurar los Datos de Inicio ");
            }
        }
    } else {
        new Mensajes().StandarWarning(this, "Ingrese todos los campos.");
    }
}//GEN-LAST:event_btnAceptarActionPerformed

private void txtNombreKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyPressed
// TODO add your handling code here:
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        btnAceptar.requestFocus();
        btnAceptarActionPerformed(null);
    }
}//GEN-LAST:event_txtNombreKeyPressed

private void txtClaveKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtClaveKeyPressed
// TODO add your handling code here:
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        btnAceptar.requestFocus();
        btnAceptarActionPerformed(null);
    }
}//GEN-LAST:event_txtClaveKeyPressed

    /**
     * @param args the command line arguments
     */


    private boolean validarcampos() {
        if (!txtNombre.getText().isEmpty()) {
            if (!txtClave.getText().isEmpty()) {
                return true;
            }
        }
        return false;
    }

    private boolean validaradmin() {
        if (txtClave.getText().compareToIgnoreCase("admin") == 0) {
            if (txtNombre.getText().compareToIgnoreCase("admin") == 0) {
                return true;
            }
        }
        return false;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnVoto;
    private com.mycsistemas.swingec.panel.CurvesPanel curvesPanel1;
    private com.mycsistemas.swingec.panel.CurvesPanel curvesPanel2;
    private com.mycsistemas.swingec.panel.ImagePanel imagePanel1;
    private com.mycsistemas.swingec.panel.ImagePanel imagePanel2;
    private javax.swing.JButton jBtnIngCancelar;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLblIngClave;
    private javax.swing.JLabel jLblIngNombre;
    private javax.swing.JLabel jLblIngSist;
    private javax.swing.JLabel jLblIngSist1;
    private javax.swing.JLabel jLblIngSist2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JPasswordField txtClave;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables
}
